package com.qst.dao.impl;

import com.qst.dao.RoleDao;
import com.qst.entity.Role;
import com.qst.utils.DBHelper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RoleMySqlDaoImpl implements RoleDao {
    @Override
    public List<Role> getAll() {
        DBHelper dbHelper=new DBHelper();
        dbHelper.setSql("Select * from role");
        ResultSet resultSet = dbHelper.executeQuery();
        List<Role> roleList=new ArrayList<>();
        try {
            while (resultSet.next()) {
                Role role=new Role(
                        resultSet.getInt(1),
                        resultSet.getString(2)
                );
                roleList.add(role);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return roleList;
    }

    @Override
    public Role getRoleByUserID(int userID) {
        Role result=null;
        DBHelper dbHelper=new DBHelper();
        String sql="Select role.roleID,roleName from role INNER JOIN " +
                "relation_user_role r on role.roleID=r.roleID  " +
                "where relation_user_role.userID="+userID;
        dbHelper.setSql(sql);
        ResultSet resultSet = dbHelper.executeQuery();
        try {
            if (resultSet.next()) {
                result=new Role(
                        resultSet.getInt(1),
                        resultSet.getString(2)
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }
}
